package nero.yncc.com.createart.utils;

import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.adapter.AdapterGoodsSpec;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.GodBean;
import nero.yncc.com.createart.bean.UserBean;
import nero.yncc.com.createart.custom.MyRecyclerView;
import nero.yncc.com.createart.interfaces.InterfaceDoSomeThing;

import static android.view.View.GONE;

/**
 * Created by nero on 17-7-5.
 */

public class PopGuige {

    @ViewInject(R.id.iv_image)
    ImageView iv_image;
    @ViewInject(R.id.tv_title)
    TextView tv_title;
    @ViewInject(R.id.tv_content)
    TextView tv_content;

    @ViewInject(R.id.tv_money)
    TextView tv_money;
    @ViewInject(R.id.lv_list_guige)
    MyRecyclerView lv_list_guige;

    @ViewInject(R.id.tv_cut)
    TextView tv_cut;
    @ViewInject(R.id.tv_num)
    TextView tv_num;
    @ViewInject(R.id.tv_add)
    TextView tv_add;
    TextView tv_please_choose;

    LinearLayout ll_root;

    Context context;
    PopupWindow popupWindow;
    TextView tv_close;

    GodBean godBean;

    View view_root;
    GodBean.Goods goods;

    JSONObject jsonObject_price;

    AdapterGoodsSpec adapterGoodsSpec;
    ArrayList<GodBean.SpecAttr> arrayList_spec;

    Button btn_addShopCar;
    UserBean userBean;

    public PopGuige(Context context, GodBean godBean, UserBean userBean) {
        this.context = context;
        this.userBean = userBean;
        view_root = LayoutInflater.from(context).inflate(R.layout.pop_chooseguige, null);
        iv_image = view_root.findViewById(R.id.iv_image);
        tv_title = view_root.findViewById(R.id.tv_title);
        tv_content = view_root.findViewById(R.id.tv_content);
        lv_list_guige = view_root.findViewById(R.id.lv_list_guige);
        tv_cut = view_root.findViewById(R.id.tv_cut);
        tv_num = view_root.findViewById(R.id.tv_num);
        tv_add = view_root.findViewById(R.id.tv_add);
        tv_money = view_root.findViewById(R.id.tv_money);
        tv_please_choose = view_root.findViewById(R.id.tv_please_choose);
        btn_addShopCar = view_root.findViewById(R.id.btn_addShopCar);
        ll_root = view_root.findViewById(R.id.ll_root);
        tv_close = view_root.findViewById(R.id.tv_close);

        popupWindow = new PopupWindow(view_root, -1, -1);
        this.godBean = godBean;
        goods = godBean.getGoods();
        goods.setNum(1);
        try {
            jsonObject_price = new JSONObject(godBean.getSpec_goods_price());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        arrayList_spec = goods.getGoods_spec_list();
        adapterGoodsSpec = new AdapterGoodsSpec(context, arrayList_spec, new InterfaceDoSomeThing() {
            @Override
            public void doSomething() {
                setGuigeMoney();
            }
        });
    }

    private void init() {
        ImageUtils.BindImage(context, iv_image, goods.getOriginal_img(), 0);
        tv_title.setText(TextUtil.getText(goods.getGoods_name(), "暂无名称"));
        tv_content.setText(TextUtil.getText(goods.getGoods_remark(), "暂无简介"));
        tv_money.setText("价格: ￥" + TextUtil.getText(goods.getShop_price(), "0"));
//        tv_num.setText(TextUtil.getText(goods.getNum() + "", "0"));
        tv_cut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int numCache = goods.getNum();
                if (numCache > 1) {
                    numCache--;
                    goods.setNum(numCache);
                    tv_num.setText(TextUtil.getText(numCache + "", "0"));
                    tv_money.setText("价格：￥" + (Double.parseDouble(price) * numCache) + "");
                }

            }
        });
        tv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        btn_addShopCar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downOrder();
            }
        });

        ll_root.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });

        tv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int numCache = goods.getNum();
                try {
                    if (numCache < Integer.parseInt(goods.getStore_count())) {
                        numCache++;
                        goods.setNum(numCache);
                        tv_num.setText(TextUtil.getText(numCache + "", "0"));
                        tv_money.setText("价格：￥" + (Double.parseDouble(price) * numCache) + "");
                    } else {
                        Toast.makeText(context, "库存不足，已是最大库存", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(context, "该商品库存不足，无法下单", Toast.LENGTH_SHORT).show();
                }


            }
        });
        lv_list_guige.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        lv_list_guige.setAdapter(adapterGoodsSpec);
        adapterGoodsSpec.notifyDataSetChanged();

        price = goods.getShop_price();
        marketPrice = goods.getMarket_price();
        if (goods.getGoods_spec_list() == null || goods.getGoods_spec_list().size() == 0) {
            tv_please_choose.setVisibility(GONE);
        }
    }

    public void show(Activity activity) {
        init();
        popupWindow.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    public boolean isShow() {
        return popupWindow.isShowing();
    }

    public void disMiss() {
        popupWindow.dismiss();
    }

    Boolean isChooseAll = true;//是否所有规格都进行了选择
    String specStr = "";
    String price = "";
    String marketPrice = "";

    public void setGuigeMoney() {
        //便利规格的选择 串联起来
//        if(arrayList_spec==null || arrayList_spec.size()==0){
//            specStr="";
//            return;
//        }
//        tv_please_choose.setText("");

//        {"goods_id": 101,"spec_list": [{"spec_id": 35,"item_id": 155}], "price": 100,"market_price": 250, "number": 1}
        specStr = "[{\"goods_id\": " + goods.getGoods_id() + ",\"spec_list\": [";
        isChooseAll = true;
        tv_num.setText("1");
        goods.setNum(1);

        String key = "";
        for (GodBean.SpecAttr specAttr : arrayList_spec) {
            if (TextUtils.isEmpty(specAttr.getChooseAttrId())) {
                isChooseAll = false;
                tv_please_choose.setText("请选择" + specAttr.getName());
                specStr = "";
                return;
            }
//            {"spec_id": 35,"item_id": 155}
            specStr += "{\"spec_id\":" + specAttr.getSpec_id() + ",\"item_id\":" + specAttr.getChooseAttrId() + "},";
            key += specAttr.getChooseAttrId() + "_";
        }
//        "price": 100,"market_price": 250, "number": 1}
        if (specStr.endsWith(","))
            specStr = specStr.substring(0, specStr.length() - 1);
        specStr += "],";
        tv_please_choose.setText("");
        if (key.length() > 0)
            key = key.substring(0, key.length() - 1);
        try {
            price = jsonObject_price.getJSONObject(key).getString("price");
            marketPrice = jsonObject_price.getJSONObject(key).getString("market_price");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (price == null || TextUtils.isEmpty(price)) {
            price = goods.getShop_price();
        }
        if (marketPrice == null || TextUtils.isEmpty(marketPrice)) {
            marketPrice = goods.getMarket_price();
        }


        tv_money.setText("价格：￥" + price);

        specStr += " \"price\": " + price + ",\"market_price\": " + marketPrice + ", \"number\": " + goods.getNum() + "}";
        specStr += "]";
        Log.e("123", specStr);
        Toast.makeText(context, specStr + "\n", Toast.LENGTH_SHORT).show();

    }


    private void downOrder() {
        setGuigeMoney();
        if (specStr == "" && (goods.getGoods_spec_list() == null || goods.getGoods_spec_list().size() < 0)) {
            Toast.makeText(context, "请先选择规格", Toast.LENGTH_SHORT).show();
            return;
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", goods.getGoods_id());
        hashMap.put("user_id", userBean.getUser_id());
        hashMap.put("content", specStr);

        new HttpUtils().post((Activity) context, Constants.API_GOODSADDCAR, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }

            @Override
            public void fail(String failMsg) {
                Toast.makeText(context, failMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

}
